from flask import Blueprint, render_template, flash, jsonify
from app.models.orders import Orders
from app.forms.orders import OrdersForm
from app.celery import pull
from celery.result import AsyncResult
from app.extensions import db
import time

bp = Blueprint('forntend_orders', __name__)



@bp.route('/')
def index():
    form = OrdersForm()
    orders = Orders.query.order_by(Orders.id.desc()).all()
    if form.errors:
        flash(form.errors, 'warning')
    return render_template('frontend/index.html', form=form, items=orders)


@bp.route('/create', methods=['POST'])
def create():
    form = OrdersForm()
    model = Orders()
    if model.save(form):
        return jsonify(success=True, data=model.to_dict())

    if form.errors:
        message = {i[0]: i[1][0] for i in form.errors.items()},
        return jsonify(success=False, message=message)

@bp.route('/pull/<int:id>')
def bills_pull(id):
    model = Orders.query.get(id)
    res = pull.delay('user_1')
    while True:
        print(res.ready())
        if res.ready():
            for i in res.result:
                if i['payer_remark']:
                    if i['payer_remark'] == model.id:
                        model.status = 9
                        db.session.commit()
            break
        time.sleep(1)

    return jsonify(success=True, message='成功')